<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <div class="search-row">
        <el-form-item
          label="是否代理"
          label-width="75px"
          prop="isProxy"
          size="mini"
        >
          <div class="manager-tags">
            <span
              class="manager-tag"
              :class="{ active: queryParams.isProxy === '已代理' }"
              @click="handleProxySelect('已代理')"
            >
              已代理
            </span>
            <span
              class="manager-tag"
              :class="{ active: queryParams.isProxy === '未代理' }"
              @click="handleProxySelect('未代理')"
            >
              未代理
            </span>
          </div>
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="opt!=='details'">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"

          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="listList"
      :cell-style="{ padding: '0px' }"
      :row-style="{ height: '30px' }"
      border
      height="450"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="序"
        type="index"
        prop="index"
        width="35"
        :index="indexMethod"
      />
      <el-table-column
        label="发布时间"
        align="center"
        prop="releaseTime"
        width="100"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.releaseTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="产品类别"
        align="center"
        prop="productType"
        width="100"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_type" :value="scope.row.productType" />
        </template>
      </el-table-column>
      <el-table-column
        label="产品名称"
        align="center"
        prop="productName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="产品介绍"
        align="center"
        prop="productRemark"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="产品规格"
        align="center"
        prop="productSpecs"
        width="120"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="是否代理"
        align="center"
        prop="isProxy"
        width="70"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.isProxy === '已代理' ? 'success' : 'danger'"
            size="mini"
          >
            {{ scope.row.isProxy }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        width="80"
        class-name="small-padding fixed-width"
        v-if="opt!=='details'"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            title="编辑"
          ></el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            title="删除"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-model="form.productName"
                placeholder="请输入产品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类别" prop="productType">
              <el-select
                v-model="form.productType"
                placeholder="请选择产品类别"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.product_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品介绍" prop="productRemark">
              <el-input
                v-model="form.productRemark"
                type="textarea"
                :rows="3"
                placeholder="请输入产品介绍"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="产品规格" prop="productSpecs">
              <el-input
                v-model="form.productSpecs"
                type="textarea"
                :rows="3"
                placeholder="请输入产品规格"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发布时间" prop="releaseTime">
              <el-date-picker
                clearable
                v-model="form.releaseTime"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择发布时间"
                style="width: 100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否代理" prop="isProxy">
              <el-select
                v-model="form.isProxy"
                placeholder="请选择是否代理"
                style="width: 100%"
              >
                <el-option label="已代理" value="已代理" />
                <el-option label="未代理" value="未代理" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="附件">
              <file-view
                :type="typeSelect"
                :businessId="form.id"
                :businessCode="businessCode"
                @change="getFile"
                style="width: 500px"
              ></file-view>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
<!--    导入-->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listList,
  getList,
  delList,
  addList,
  updateList,
} from "@/api/list/list";
import FileView from "@/components/FileView/index";
import Template from "@/views/membertemplate/index.vue";
import {getToken} from "../../utils/auth";
export default {
  name: "List",
  dicts: ["product_type"],
  components: {
    Template,
    FileView,
  },
  props: {
    bId: {
      type: String,
      default: "",
    },
    opt:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      typeSelect: 0,
      index: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      listList: [],
      // 弹出层标题
      title: "",
      businessCode: "productRelease",
      // 是否显示弹出层
      open: false,
      //导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "导入产品清单",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        enterpriseId: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url:
          process.env.VUE_APP_BASE_API +
          "/product/list/importData?enterpriseId=" +
          this.bId +
          "",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        productType: null,
        productName: null,
        productRemark: null,
        productSpecs: null,
        releaseTime: null,
        isProxy: null,
        enterpriseId: null,
        organizationId: null,
        organizationName: null,
        creationTime: null,
        createId: null,
        createName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
          {
            max: 50,
            message: "产品名称长度不能超过50个字符",
            trigger: "blur",
          },
        ],
        productType: [
          { required: true, message: "请选择产品类别", trigger: "change" },
        ],
        productSpecs: [
          { required: true, message: "产品规格不能为空", trigger: "blur" },
          {
            max: 50,
            message: "产品规格长度不能超过50个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      this.queryParams.enterpriseId = this.bId;
      listList(this.queryParams).then(response => {
        this.listList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "/product/list/importTemplate",
        {},
        `供应商产品清单.xlsx`
      );
    },
    //文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
      this.getList();
      this.upload.open = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productType: null,
        productName: null,
        productRemark: null,
        productSpecs: null,
        releaseTime: null,
        isProxy: null,
        organizationId: null,
        organizationName: null,
        creationTime: null,
        createId: null,
        createName: null,
        enterpriseId: null,
      };
      this.resetForm("form");
    },
    handleImport() {
      this.upload.open = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleProxySelect(value) {
      this.queryParams.isProxy =
        this.queryParams.isProxy === value ? undefined : value;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/product/list/export', {
        ...this.queryParams
      }, `供应商产品清单.xlsx`)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.releaseTime = new Date();
      this.form.enterpriseId = this.enterpriseId;
      this.typeSelect = 0;
      this.title = "添加产品清单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getList(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.typeSelect = 1;
        this.title = "修改产品清单信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.enterpriseId=this.bId;
            updateList(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.enterpriseId=this.bId;
            addList(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除产品名称为"' + row.productName + '"的数据项？')
        .then(function () {
          return delList(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    getFile(data) {
      console.log(JSON.stringify(data));
    },
  },
};
</script>
<style scoped>
.manager-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;

  .manager-tag {
    padding: 0 12px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
      color: #409eff;
    }

    &.active {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
    }
  }
}
</style>
